Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

128
Vistas
[Node.js]Access json file in another folder with file.readFile

Im trying to access json data from a local server

  • js(folder)
    • item_data.json
    • server.js
    • client.js
  • index.html

In my client.js

var xhttp
window.onload = function(){
  requestData("http://localhost:8000/js/item_data.json");
}

function requestData(URL){
  xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = processData;
  xhttp.open("GET", URL, true);
  console.log(xhttp);  //it prints information with status: 0
}

function processData(){
  console.log(xhttp.status); //prints 0
  if(xhttp.readyState === XMLHttpRequest.DONE && xhttp.status === 200) { // do something }
  else{ console.log("ERROR"); } //This is always printed
}

In my server.js

const http = require("http");
const file = require("fs");
const host = "localhost";
const port = 8000;

const server = http.createServer(processRequest);

function processRequest(request, response){
  if(request.url === "/index.html"){
    file.readFile('../index.html', 'utf8', function(err, contents) {
      if(err){
        response.writeHead(500, { "Content-Type": "text/html"});
        response.end();
        return;
      }
      response.writeHead(200, { "Content-Type": "text/html"});
      response.end(contents);
  });
  else if(request.url === "/js/item_data.json"){
    file.readFile('item_data.json', 'utf8', function(err, contents) {
        if(err){
          response.writeHead(500, { "Content-Type": "application/javascript"});
          response.end();
          return;
        }
        response.writeHead(200, { "Content-Type": "application/javascript"});
        response.end(contents);
    });
  }
}

I have tried to change the content type to application/json
Tried to use /js/item_data.json
And request.url === "/item_data.json"
They both not working

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda